package dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import dto.IntrebariDTO;
import dto.RaspunsuriDTO;
import entities.Intrebari;
import entities.Raspunsuri;

@Stateless
public class RaspunsuriDAO implements RaspunsuriDAORemote {

	@PersistenceContext
	EntityManager em;

	Conversion conv = new Conversion();

	@Override
	public List<RaspunsuriDTO> getRaspunsuriByIntrebareId(int id) {
		Query query = em.createNamedQuery("getRaspunsuriByIntrebareId");
		query.setParameter("in_idParam", id);
		List<Raspunsuri> raspunsuri = query.getResultList();
		List<RaspunsuriDTO> rasp = new ArrayList<RaspunsuriDTO>();
		for (int i = 0; i < raspunsuri.size(); i++) {
			RaspunsuriDTO r = new RaspunsuriDTO();
			// r.setId_intrebare(raspunsuri.get(i).getId_intrebare());
			r.setId(raspunsuri.get(i).getId());
			r.setRaspuns(raspunsuri.get(i).getRaspuns());
			rasp.add(r);
		}

		return rasp;
	}

	@Override
	public void create(RaspunsuriDTO raspunsuri) {
		try {
			Raspunsuri r = new Raspunsuri();
			r.setRaspuns(raspunsuri.getRaspuns());
			Intrebari i = new Intrebari();
			i = conv.convertIntrebareDTO(raspunsuri.getIntrebari());
			r.setIntrebari(i);
			em.persist(r);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void delete(RaspunsuriDTO raspuns) {
		int id = raspuns.getId();
		Raspunsuri r = new Raspunsuri();
		r = em.find(Raspunsuri.class, id);
		em.remove(r);

	}

	@Override
	public void update(RaspunsuriDTO raspuns) {
		Raspunsuri r = new Raspunsuri();
		r = em.find(Raspunsuri.class, raspuns.getId());
		r.setRaspuns(raspuns.getRaspuns());

	}

	@Override
	public List<RaspunsuriDTO> getRaspunsuriByIntrebare(IntrebariDTO in) {

		Intrebari i = new Intrebari();
		i = conv.convertIntrebareDTO(in);
		Query query = em.createNamedQuery("getRaspunsuriByIntrebareId");
		query.setParameter("ch_idParam", i);
		List<Raspunsuri> raspunsuri = query.getResultList();
		List<RaspunsuriDTO> rasp = new ArrayList<RaspunsuriDTO>();
		for (int ii = 0; ii < raspunsuri.size(); ii++) {
			RaspunsuriDTO rr = new RaspunsuriDTO();
			rr = conv.convertRaspunsToDTO(raspunsuri.get(ii));
			rasp.add(rr);
		}
		return rasp;
	}
}
